<?php
namespace addons\Insurance\merchant\controllers;
use Yii;
use common\traits\Curd;
use common\helpers\ExcelHelper;
use common\models\base\SearchModel;
use common\enums\StatusEnum;
use addons\Insurance\common\helpers\ImportHelper;
use addons\Insurance\common\models\Insurance;
use addons\Employees\common\models\Employees;

class DefaultController extends BaseController
{
    use Curd;

    public $modelClass = Insurance::class;

    public function actionIndex()
    {
        $searchModel = new SearchModel([
            'model' => $this->modelClass,
            'scenario' => 'default',
            'relations' => ['employees' => ['name','idcard']], // 关联 member 表的 nickname 字段
            'partialMatchAttributes' => ['title', 'employees.name', 'employees.idcard'], // 模糊查询，注意 member_nickname 为关联表的别名 表名_字段
            'defaultOrder' => [
                'id' => SORT_DESC
            ],
            'pageSize' => $this->pageSize
        ]);

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->query->andFilterWhere([Insurance::tableName().'.merchant_id' => $this->getMerchantId()]);
        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
            'employees' => Employees::getDropDown(),

        ]);
    }

    public function actionCreate()
    {
        $id = Yii::$app->request->get('id', null);
        $model = $this->findModel($id);
        // ajax 校验
        $this->activeFormValidate($model);

        if ($model->load(Yii::$app->request->post())) {

            return $model->save()
                ? $this->redirect(['index'])
                : $this->message($this->getError($model), $this->redirect(['index']), 'error');
        }
        return $this->renderAjax('create', [
            'model' => $model,
            'employees' => Employees::getDropDown(),

        ]);
    }
    public function actionEdit()
    {
        $id = Yii::$app->request->get('id', null);
        $model = $this->findModel($id);
        // ajax 校验
        $this->activeFormValidate($model);

        if ($model->load(Yii::$app->request->post())) {

            return $model->save()
                ? $this->redirect(['index'])
                : $this->message($this->getError($model), $this->redirect(['index']), 'error');
        }
        return $this->renderAjax('edit', [
            'model' => $model,
            'employees' => Employees::getDropDown(),

        ]);
    }
    public function actionDelete($id)
    {
        if ($this->findModel($id)->delete()) {
            return $this->message("删除成功", $this->redirect(['index']));
        }

        return $this->message("删除失败", $this->redirect(['index']), 'error');
    }


    /**
     * 导入
     */
    public function actionImport()
    {
        if (Yii::$app->request->isPost) {
            try {
                $file = $_FILES['excelFile'];
                $data = ExcelHelper::import($file['tmp_name'], 2);
                ImportHelper::Insurance($data);
            } catch (\Exception $e) {
                return $this->message($e->getMessage(), $this->redirect(['index']), 'error');
            }
            return $this->message('导入成功', $this->redirect(['index']));
        }
        return $this->render('import', [

        ]);
    }
    /**
     * 下载
     */
    public function actionDownload()
    {
        $file = 'insurance.xlsx';
        $path = Yii::getAlias('@addons') . '/Insurance/common/files/' . $file;
        Yii::$app->response->sendFile($path, Yii::$app->request->get('type').'_' . time() . '.xls');
    }
    /**
     * 导出
     */
    public function actionExport()
    {
        $header = [
            ['员工姓名', 'employees.name'],
            ['身份证', 'employees.idcard'],
            ['交纳金额', 'pay_amount'],
            ['交纳时间', 'pay_time']
        ];

        $list = $this->modelClass::find()->select('*')
            ->andWhere(['status' => StatusEnum::ENABLED,'merchant_id'=>Yii::$app->user->identity->merchant_id])
            ->with('employees')
            ->asArray()
            ->all();
        return ExcelHelper::exportData($list, $header);
    }
    protected function findModel($id)
    {
        if (empty($id) || empty(($model = $this->modelClass::findOne(['id' => $id, 'merchant_id' => $this->getMerchantId()])))) {
            $model = new $this->modelClass;
            return $model->loadDefaultValues();
        }

        return $model;
    }
}
